package com.example.demo_news.security;

import com.example.demo_news.Repository.UserPepository;
import com.example.demo_news.entity.MyUser;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class MyUserDetailService implements UserDetailsService{

    @Autowired
    private UserPepository userPepository;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MyUser user=userPepository.findUserByusername(username);
        if(user==null){
            throw new UsernameNotFoundException("用户名不存在");
            //数据库没有用户名,认证失败
        }
        //添加角色后缀
        String role=user.getRole();
        List<GrantedAuthority>auths=AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_"+role);
           //从查询数据库返回user对象,得到用户名和密码
        return new User(user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()),auths);
    }
    
}
